<template>
    <div>
        <navigation-bar :customTitle="curTitle">
            <div class="searchContent">
                <el-select v-model="optionValue" style="width: 100px" size="mini">
                    <el-option v-for="item in options" :value="item.value" :key="item.value" :label="item.label"></el-option>
                </el-select>
                <el-input
                    v-model="userName"
                    placeholder="请输入用户名称"
                    size="mini"
                    style="width: 150px; margin-right: 10px; margin-left: 10px"
                ></el-input>
                <custom-button type="search" style="margin-right: 10px" @searchClick="searchClick"></custom-button>
                <custom-button type="reset" style="margin-right: 10px" @resetClick="resetClick"></custom-button>
                <custom-button type="add" style="margin-right: 10px" @addClick="addClick"></custom-button>
            </div>
        </navigation-bar>

        <div>
            <table-index
                :dataSource="dataSource"
                :tableColumns="tableColumns"
                :btnList="btnList"
                :pageSize="pageSize"
                :pageCount="pageCount"
                :pageNo="pageNo"
                @pageChange="pageChange"
                @editRow="editRow"
                @viewRow="viewRow"
                @deleteRow="deleteRow"
                selection
                @handleSelectionChange="handleSelectionChange"
                @resetPwdRow="resetPwdRow"
                :height="secondTableHeight"
            ></table-index>
        </div>

        <div v-if="dialogShow">
            <custom-dialog :title="dialogTitle" size="large" @dialogClose="dialogClose">
                <form-index :formConfig="formConfig" @submit="submit" :type="type" @formInputChange="formInputChange" ref="form">
                    <!--  <div>这里还可以插入其它内容进行拓展</div> -->
                </form-index>
            </custom-dialog>
        </div>

        <div v-if="dialogResetShow">
            <custom-dialog title="重置密码" size="tiny" @dialogClose="dialogResetShow = false">
                <form-index
                    :formConfig="formResetConfig"
                    @submit="resetSubmit"
                    type="edit"
                    @formInputChange="formInputChange"
                    ref="form"
                    labelwidth="80px"
                >
                    <!--  <div>这里还可以插入其它内容进行拓展</div> -->
                </form-index>
            </custom-dialog>
        </div>
    </div>
</template>

<script>
import {userManageForm} from '@/assets/form/managementCenter/systemManage/userManage'
import {resetPwdForm} from '@/assets/form/managementCenter/systemManage/resetPwd'
import customDialog from '@/components/customComponents/customDialog'
import customButton from '@/components/customComponents/customForm/customButton'
import formIndex from '@/components/customComponents/customForm/formIndex'
import tableIndex from '@/components/customComponents/customeTable/iviewTable/singleViewTable'
import navigationBar from '@/components/customComponents/managementCenter/navigationBarCustomTitle'
import {AjaxCommon} from '@/libs/apiCommon'
import {CardId} from '@/libs/cardId'
import {PopupCommon} from '@/libs/popupCommon'
import {Utility} from '@/libs/utility'
export default {
    components: {
        navigationBar,
        customButton,
        tableIndex,
        customDialog,
        formIndex
    },
    data() {
        return {
            dialogResetShow: false,
            optionValue: 'name',
            options: [
                {
                    value: 'name',
                    label: '登录名'
                },
                {
                    value: 'realname',
                    label: '真实姓名'
                }
            ],
            orgInfo: {},
            secondTableHeight: document.body.clientHeight - 225,
            selectOrgList: [],
            userName: null,
            status: '',
            curTitle: '用户管理',
            statusList: Utility.getDictList('status'),
            // table 相关参数  begin
            dataSource: [],
            tableColumns: [
                //               {
                //   "LoginName": "sample string 1", // 登录名
                //   "ParentId": "sample string 2",
                //   "RealName": "sample string 3", // 真实姓名
                //   "Password": "sample string 4", // 密码
                //   "Gender": 5,// 性别
                //   "Address": "sample string 6", 、// 住址
                //   "Phone": "sample string 7", // 手机号码
                //   "Email": "sample string 8", // 邮箱
                // }
                {
                    type: 'selection',
                    width: 60,
                    align: 'center'
                },
                {
                    type: 'index',
                    width: 60,
                    align: 'center'
                },
                {
                    key: 'user_id',
                    title: '登录名'
                },
                {
                    key: 'user_name',
                    title: '真实姓名'
                },
                {
                    key: 'user_sex',
                    title: '性别',
                    slot: 'user_sex'
                },
                {
                    key: 'user_m_tel',
                    title: '手机号码'
                },

                {
                    key: 'user_email',
                    title: '用户邮箱'
                },
                {
                    key: 'user_address',
                    title: '住址'
                },
                {
                    key: 'tole_tag',
                    title: '角色'
                },
                {
                    key: 'is_enable',
                    title: '是否启用',
                    slot: 'is_enable'
                },

                {
                    title: '操作',
                    slot: 'action',
                    width: 160,
                    align: 'center'
                }
            ],
            btnList: ['edit', 'resetPwd', 'delete'],
            pageSize: 20,
            pageCount: 100,
            pageNo: 1,
            // table 相关参数  end

            // 弹窗是否显示
            dialogShow: false,
            // 弹窗标题 (新增修改不同)
            dialogTitle: '',

            // form的配置信息
            formConfig: null,
            type: 'add',

            formResetConfig: resetPwdForm(''),
            roleList: []
        }
    },
    created() {
        this.getData()
    },
    methods: {
        getData() {
            this.getRoleList(() => {
                const role = this.roleList
                this.formConfig = userManageForm('add', role)
            })
        },
        // 获取角色列表
        getRoleList() {
            let self = this
            let params = `/api/Role/GetRoleTreeData`
            AjaxCommon(params, 'get', null).then((res) => {
                if (res?.data?.Code == 200) {
                    const data = res?.data.Message
                    data?.map((t) => {
                        t?.children?.map((b) => {
                            b.PARENT_ROLE_NAME = t.ROLE_NAME
                            return b
                        })
                    })
                    self.roleList = data
                }
            })
        },
        getOrgInfo(item) {
            this.orgInfo = item
            this.curTitle = item.fullName
            this.searchClick()
        },
        getHeight() {
            this.secondTableHeight = document.body.clientHeight - 225
        },
        customClick(isTrue) {
            this.useOrg(isTrue)
        },
        handleSelectionChange(d) {
            this.selectOrgList = d
        },
        resetPwdRow(d) {
            let formConfigItem = this.formResetConfig
            formConfigItem.map((t) => {
                Object.keys(t).map((res) => {
                    if (t.fieldName == 'user_id') {
                        t.filedValue = d['user_guid']
                    } else if (t.fieldName == 'LoginName') {
                        t.filedValue = d['user_id']
                    } else if (t.fieldName == 'RealName') {
                        t.filedValue = d['user_name']
                    }
                })
            })
            this.formResetConfig = formConfigItem
            this.dialogResetShow = true
        },
        formInputChange(e) {
            if (e.filedName == 'idCard') {
                const data = CardId.getInfoByCardId(e.value)
                if (data) {
                    let newData = e.allData
                    newData['birthday'] = data.birthday
                    newData['sex'] = data.sex
                    this.$refs.form.changeFormValue(newData)
                }
            }
        },
        resetSubmit(d) {
            // delete d.LoginName
            // delete d.RealName
            let self = this
            AjaxCommon('/api/User/ResetPass', 'post', d).then((res) => {
                if (res?.data?.Code == 200) {
                    PopupCommon.notify('success', '重置成功')
                    self.initPage()
                    self.dialogResetShow = false
                } else {
                    const msg = res?.data?.Message
                    if (msg) {
                        PopupCommon.notify('error', msg)
                    }
                }
            })
        },
        submit(d) {
            let self = this
            d.UserRoles = d.tole_tag.toString()

            if (d.UserGUID) {
                AjaxCommon('/api/User/EditUser', 'post', d).then((res) => {
                    if (res?.data?.Code == 200) {
                        PopupCommon.notify('success', '编辑成功')
                        self.initPage()
                        self.dialogClose()
                    } else {
                        const msg = res?.data?.Message
                        if (msg) {
                            PopupCommon.notify('error', msg)
                        }
                    }
                })
            } else {
                d.Enable = '1'
                delete d.UserGUID
                // 根据类型调用不同接口
                let url = '/api/User/AddUser'
                AjaxCommon(url, 'post', d).then((res) => {
                    if (res?.data?.Code == 200) {
                        PopupCommon.notify('success', '新增成功')
                        self.initPage()
                        self.dialogClose()
                    } else {
                        const msg = res?.data?.Message
                        if (msg) {
                            PopupCommon.notify('error', msg)
                        }
                    }
                })
            }
        },
        dialogClose() {
            this.dialogShow = false
        },
        searchClick() {
            this.pageNo = 1
            this.initPage()
        },
        resetClick() {
            this.userName = null
            this.searchClick()
        },
        addClick() {
            this.formConfig = userManageForm('add', this.roleList)
            let formConfigItem = this.formConfig
            formConfigItem.map((t) => {
                Object.keys(t).map((res) => {
                    if (res == 'fieldName') {
                        t.filedValue = ''
                    }
                })
            })
            this.formConfig = formConfigItem
            this.type = 'add'
            this.dialogTitle = '新增'
            this.dialogShow = true
        },
        // 分页点击事件
        pageChange(p) {
            this.pageNo = p
            this.initPage()
        },
        async editRow(d) {
            this.formConfig = userManageForm('edit', this.roleList)
            // 先获取组织机构的用户信息
            this.type = 'edit'
            let formConfigItem = this.formConfig
            formConfigItem.map((t) => {
                Object.keys(t).map((res) => {
                    if (t.fieldName == 'UserGUID') {
                        t.filedValue = d['user_guid']
                    } else if (t.fieldName == 'LoginName') {
                        t.filedValue = d['user_id']
                    } else if (t.fieldName == 'RealName') {
                        t.filedValue = d['user_name']
                    } else if (t.fieldName == 'Gender') {
                        t.filedValue = d['user_sex']
                    } else if (t.fieldName == 'Phone') {
                        t.filedValue = d['user_m_tel']
                    } else if (t.fieldName == 'Email') {
                        t.filedValue = d['user_email']
                    } else if (t.fieldName == 'Address') {
                        t.filedValue = d['user_address']
                    } else if (t.fieldName == 'tole_tag') {
                        t.filedValue = d['tole_tag']?.split(',') ?? []
                    }
                })
            })
            console.log(formConfigItem)
            this.formConfig = formConfigItem
            this.dialogTitle = '编辑'
            setTimeout(() => {
                this.dialogShow = true
            }, 100)
        },
        viewRow(d) {
            this.type = 'look'
            let formConfigItem = this.formConfig
            formConfigItem.map((t) => {
                Object.keys(t).map((res) => {
                    if (res == 'fieldName') {
                        t.filedValue = d.data[t[res]]
                    }
                })
            })
            this.formConfig = formConfigItem
            this.dialogTitle = '查看'
            this.dialogShow = true
        },
        // 启用或禁用组织机构 isTrue  true禁用 false 不禁用
        useOrg(isTrue) {
            const selectOrgList = this.selectOrgList
            if (selectOrgList.length < 1) {
                PopupCommon.notify('info', '请选择至少一个机构')
                return
            }
            const id = selectOrgList.map((t) => t.id).toString()
            let self = this
            let apiUrl = ''
            let tipMsg = ''
            if (isTrue) {
                apiUrl = `api/OrgSysManage/ChangeOrgsDisable`
                tipMsg = '禁用'
            } else {
                apiUrl = 'api/OrgSysManage/ChangeOrgsEnable'
                tipMsg = '启用'
            }
            AjaxCommon(apiUrl, 'post', {orgids: id}).then((res) => {
                console.log(res, 'res...............')
                if (res?.data?.Code == 200) {
                    PopupCommon.notify('success', tipMsg + '成功')
                    self.initPage()
                } else {
                    const msg = res?.data?.Message
                    if (msg) {
                        PopupCommon.notify('error', msg)
                    }
                }
            })
        },

        deleteRow(d) {
            const id = d.user_id
            let self = this
            AjaxCommon(`/api/user/DeleteUser/${id}`, 'post', {}).then((res) => {
                if (res?.data?.Code == 200) {
                    PopupCommon.notify('success', '删除成功')
                    self.initPage()
                } else {
                    const msg = res?.data?.Message
                    if (msg) {
                        PopupCommon.notify('error', msg)
                    }
                }
            })
        },
        // 初始化事件
        initPage() {
            let self = this
            let params = `/api/User/GetUsersByOrg?PageSize=${this.pageSize}&PageIndex=${this.pageNo}`
            if (this.userName) {
                params += `&value=${this.userName}&where=${this.optionValue}`
            }
            // const params = `/api/user/by-org/page/${this.pageNo}/size/${this.pageSize}`
            AjaxCommon(params, 'get', null).then((res) => {
                console.log(res, 'res...........')
                if (res?.data?.Code == 200) {
                    const data = res?.data.Message
                    console.log(data?.rows, 'data?.rows...')
                    self.dataSource = data?.rows
                    self.pageCount = parseInt(data?.total)
                } else {
                    PopupCommon.notify('error', res?.data?.msg)
                }
            })
        }
    },
    mounted() {
        this.$nextTick(() => {
            this.getHeight()
            this.initPage()
        })

        /*窗口自适应，关键代码*/
        window.onresize = () => {
            this.getHeight()
        }
    }
}
</script>

<style></style>
